package com.bainuo.doctor.common.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ScrollView;

import com.blankj.utilcode.utils.LogUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by SeenFar on 16/6/21.
 */
public class BNKeyBoardManager {


    public View mRootView;
    public int mScreenHeight;
    public int mDelay=300;
    private int maxBottom;
    public boolean isShow;

    private ViewTreeObserver.OnGlobalLayoutListener layoutListener;

    private KeyboardListener listener;


    public interface KeyboardListener{

        void onKeyboardShow(int keyBoardHeight);
        void onKeyboardHiden(int keyBoardHeight);

    }

    public void setKeyboardListener(KeyboardListener listener){
        this.listener = listener;
    }


    public void setRootView(Activity activity,View root) {
        setRootView(activity,root,WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                |WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    public void setRootViewResizeShowKeboard(Activity activity,View root) {
        setRootView(activity,root,WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                |WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    public void setRootViewPan(Activity activity,View root) {
        setRootView(activity,root,WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
                            |WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    public void setRootViewPanShowKeboard(Activity activity,View root) {
        setRootView(activity,root,WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
                |WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    public void setRootView(Activity activity,View root,int mode) {

        setRootView(root);
        Window window = activity.getWindow();
        if (window != null){
            window.setSoftInputMode(mode);
            mScreenHeight =activity.getWindowManager().getDefaultDisplay().getHeight();
        }
    }




    private Rect rect = new Rect();
    public boolean isKeyboardVisible() {
        mRootView.getWindowVisibleDisplayFrame(rect);
//        LogUtils.e("isKeyboardVisible---------------"+rect.bottom);
        return rect.bottom < mScreenHeight * 4 / 5;
    }

    public int getKeyboardHeight(){
        mRootView.getGlobalVisibleRect(rect);
        if (rect.bottom == 0)
            return 0;
        return mScreenHeight-rect.bottom;
    }


    boolean first = true;
    public void setRootView(final View view) {
        if (view == null)
            return;

        mRootView = view;
        layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                if (mRootView.getHeight() == 0)
                    return;





                final Rect r = new Rect();
//                final Rect r3 = new Rect();
                mRootView.getWindowVisibleDisplayFrame(r);
//                mRootView.getLocalVisibleRect(r3);
//
//                View view =  mRootView.getRootView();




                if (r.bottom >= mScreenHeight*4/5){
                    //键盘未弹出

                    if(isShow){

                        recoveryView();
                        isShow = false;
                        if (listener != null ){
                            listener.onKeyboardHiden(mScreenHeight-r.bottom);
                        }



//                        Animation animation =
//                            new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
//                                Animation.RELATIVE_TO_SELF, 0,
//                                Animation.ABSOLUTE,0
//                                , Animation.ABSOLUTE, 0);
//
//                                animation.setDuration(300);
//                                animation.setFillEnabled(true);
//                                animation.setFillAfter(true);

                    }
//                    ObjectAnimator.ofFloat()

                }else {
                    //键盘弹出
                    if(!isShow){
                        isShow = true;
                        if (listener != null){
                            listener.onKeyboardShow(mScreenHeight-r.bottom);
                        }
                    }
                }

//
//                if (r.bottom == maxBottom && isShow){
//                    isShow=false;
//
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            mRootView.getWindowVisibleDisplayFrame(r);
//                            if (listener != null && r.bottom == maxBottom){
//                                listener.onKeyboardHiden(maxBottom-r.bottom);
//                            }
//                        }
//                    },mDelay);
//                }
            }
        };


        view.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);


//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            view.getViewTreeObserver().addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
//                @Override
//                public void onDraw() {
//                    if (isKeyboardVisible()){
//
//                        if (!isShow){
//                            isShow = true;
//                            if (listener != null ){
//                                LogUtils.e("onKeyboardShow---------------");
//                                listener.onKeyboardShow(536);
//                            }
//                        }
//
//                    }else{
//                        if (isShow){
//                            isShow = false;
//                            if (listener != null ){
//                                listener.onKeyboardHiden( 0);
//                            }
//                        }
//
//
//                    }
//
//                }
//            });
//        }

//        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            @Override
//            public boolean onPreDraw() {
//
//                if (isKeyboardVisible()){
//
//                    if (!isShow){
//                        isShow = true;
//                        if (listener != null ){
//                            listener.onKeyboardShow(getKeyboardHeight());
//                        }
//                    }
//
//
//
//                }else{
//                    if (isShow){
//                        isShow = false;
//                        if (listener != null ){
//                            listener.onKeyboardHiden( 0);
//                        }
//                    }
//
//
//                }
//                return true;
//            }
//        });

    }

    public void removeRootView(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);
        }
    }


//    public void adjuctView(View view,int bottomMargin,int kh){
//
////        adjuctView(mRootView,view,bottomMargin,kh);
//    }


    public void adjuctView(final ScrollView scrollView,View view, int bottomMargin, int kh) {

        final Rect rb = ViewUtil.getLocationInWindow(view);
        Rect rt = ViewUtil.getLocation(mRootView);
//        int rb = rt.bottom;

//        final int adj = -kh + (rb - vb) - bottomMargin;
//        final int moveDelta = kh - (rb - vb);
//
//        LogUtils.e("adjuctView--->" + vb + "   " + adj);

        final  int bbb= scrollView.getScrollY()+rb.bottom-scrollView.getHeight();

        MyUtil.runLoop(0, new MyUtil.Loop() {
            @Override
            public boolean doexec() {

                scrollView.scrollTo(0,bbb);
//                scrollView.scrollTo(0,100000);
                return false;
            }
        });
//        scrollView.scrollTo(0,100000);



//        if (adj > 0)
//            return;
//        mRootView.setY(adj);
    }

    public void adjuctView(View view,int bottomMargin,int kh){

        int vb = ViewUtil.getLocation(view).bottom;
        Rect rt = ViewUtil.getLocation(mRootView);
        int  rb = rt.bottom;

        final int adj = -kh+(rb-vb)-bottomMargin;
//        final int moveDelta = kh-(rb-vb);
//
//        LogUtils.e("adjuctView--->"+vb+"   "+adj);

        if (adj > 0)
            return;
        mRootView.setY(adj);



//        int vb = bottom;
//        Rect rt = ViewUtil.getLocation(mRootView);
//        int  rb = rt.bottom;
//
//        final int adj = -kh+(rb-vb)-bottomMargin;
//        final int moveDelta = kh-(rb-vb);
//
//        LogUtils.e("adjuctView--->"+vb+"   "+adj);

//        if (adj > 0)
//            return;
//        mRootView.setY(adj);



//        ObjectAnimator.ofFloat(mRootView,"translationY",0,adj+moveDelta).setDuration(300).start();


//        mRootView.clearAnimation();
//        Animation animation =
//                    new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
//                            Animation.RELATIVE_TO_SELF, 0,
//                            Animation.ABSOLUTE,0
//                            , Animation.ABSOLUTE, adj+moveDelta);
//
//            animation.setDuration(300);
//            animation.setFillEnabled(true);
//            animation.setFillAfter(true);
//
//            animation.setInterpolator(new Interpolator() {
//                @Override
//                public float getInterpolation(float input) {
//
//                    mRootView.setY((adj+moveDelta)*input);
//                    LogUtils.e(" ppppp ---------->"+input);
//                    return 0;
//                }
//            });
//
//        view.startAnimation(animation);
////            animation.start();
//
////
//        animation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            @Override
//            public void onAnimationEnd(Animation animation) {
////                mRootView.clearAnimation();
////                mRootView.setTranslationY(0);
////                mRootView.setTop(0);
////                mRootView.setY(adj);
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
    }

//    Map<EditText,Integer> localMap = new HashMap<>();
//
//    public void addEditText(final EditText editText){
//
//        editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                if (editText.getHeight() != 0 && !localMap.containsKey(editText)){
//                    localMap.put(editText,ViewUtil.getLocation(editText).bottom);
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//                        editText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    }
//                }
//            }
//        });
//
//    }




    public void recoveryView(){
        mRootView.setY(0);
    }

    public static void setKeyBoardState(View v,boolean state){

        if (state == true){

            v.requestFocus();
            InputMethodManager inputManager =
                    (InputMethodManager)v.getContext().getSystemService( Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(v, 0);

//            inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
//                    InputMethodManager.HIDE_IMPLICIT_ONLY);

        }else{


            InputMethodManager inputManager =
                    (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//            inputManager.showSoftInput(v, 0);
            inputManager.hideSoftInputFromWindow(
                    v.getApplicationWindowToken(),0 );

        }

    }

}
